package com.woniuxy.microfundservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.woniuxy.bean.ResultBean;
import com.woniuxy.microfundservice.bean.trend.FundTrendMsg;
import com.woniuxy.microfundservice.bean.trend.TrendRes;
import com.woniuxy.microfundservice.service.FundTrendService;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static com.woniuxy.microfundservice.util.ErrorEntity.FAIL_GET_TREND;

/**
 * Auther: yeyang  <br/>
 * Date: 2021/4/15 0015:下午 7:52  <br/>
 * Description:
 */
@Service
public class FundTrendServiceImpl implements FundTrendService {
    @Resource
    private RestTemplate restTemplate;


    @Override
    public ResultBean getTrend(int fundCode, String startDate, String endDate) {
        String key=String.format("%06d",fundCode);
        String url="https://api.doctorxiong.club/v1/fund/detail?code=" + key+"&startDate="+startDate+"&endDate"+endDate;
        FundTrendMsg fundTrendMsg = restTemplate.getForObject(url, FundTrendMsg.class);
        //取出走势图数组
        String[][] netWorthData = fundTrendMsg.getData().getNetWorthData();
        if(netWorthData.length==0){
            return ResultBean.builder().code(705).msg(FAIL_GET_TREND).build();
        }
        List<Double> growth=new ArrayList<>();
        List<Double> value=new ArrayList<>();
        List<String> date=new ArrayList<>();
        //取出走势图数据放进list
        for (String[] n : netWorthData) {
            //取出基金净值涨幅
            String s = n[2];
            double g = Double.parseDouble(s);
            growth.add(g);
            //取出基金净值
            String s1 = n[1];
            double g1 = Double.parseDouble(s1);
            value.add(g1);
            //取出日期
            String s2 = n[0];
            date.add(s2);
        }
        //将走势图数据放进返回对象
        TrendRes res=new TrendRes();
        res.setGrowth(growth);
        res.setValue(value);
        res.setDate(date);

        return ResultBean.builder().code(200).data(res).build();
    }
}
